#include "byte_array.h"
#include <stdlib.h>
#include <unistd.h>

struct byte_array *byte_array_new()
{
    struct byte_array *array = calloc(1, sizeof(struct byte_array));

    return array;
}

void byte_array_free(struct byte_array *array)
{
    if (array->data != NULL) {
        free(array->data);
    }
    if (array != NULL) {
        free(array);
    }
}

int byte_array_size(struct byte_array *array)
{
    return array->len;
}

int byte_array_set_size(struct byte_array *array, ssize_t sz)
{
    if (sz <= array->room) {
        array->len = sz;
    } else {
        void *data = calloc(1, sz);
        memcpy(data, array->data, array->room);
        if (array->data != NULL) {
            free(array->data);
        }
        array->data = data;
        array->len = sz;
    }
    return array->len;
}

void byte_array_append(struct byte_array *array, const void *o, ssize_t sz)
{
    ssize_t need_sz = array->room;
    if ((sz + array->len - array->room) > 0) {
        need_sz = sz + array->len - array->room;
        array->room = need_sz;

        void *data = calloc(1, need_sz);
        memcpy(data, array->data, array->len);
        if (array->data != NULL) {
            free(array->data);
        }
        array->data = data;
    }
    memcpy(array->data+array->len, o, sz);

    array->len += sz;
}

void byte_array_prepend(struct byte_array *array, const void *o, ssize_t sz)
{
    ssize_t need_sz = array->room;
    if ((sz + array->len - array->room) > 0) {
        need_sz = sz + array->len - array->room;
        array->room = need_sz;
    } else {
        need_sz = array->room;
    }
    void *data = calloc(1, need_sz);
    memcpy(data, o, sz);
    memcpy(data, array->data, array->len);
    if (array->data != NULL) {
        free(array->data);
    }
    array->data = data;

    array->len += sz;
}


